<?php
/**
 *  PayController.class.php
 * ============================================================================
 * 版权所有 (C) 2015-2016 壹尚科技有限公司，并保留所有权利。
 * 网站地址:   http://www.ethank.com.cn
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * Author: 勾国印 (gouguoyin@ethank.com.cn) 
 * Date: 2015年8月13日 下午5:13:14  
*/
namespace Home\Controller;
use Think\Controller;
//微信支付类

include_once(SPAPP_PATH."Lib/weixing/WxPay.Api.php");
include_once(SPAPP_PATH."Lib/weixing/WxPay.JsApiPay.php");
include_once(SPAPP_PATH."Lib/weixing/log.php");
class PayController extends BaseController {





	public function getBaseInfo(){
		$post_data=json_encode($_POST);
		$appid='wx3c484176a1ad105d';
		$redirect_uri=urlencode('http://dwc.gametu.com/think/index.php?g=Home&m=Pay&a=index');
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state='.$post_data.'#wechat_redirect';
		//var_dump($url);
		header("location:".$url);
	}

	//获取access_token过程中的跳转uri，通过跳转将code传入jsapi支付页面
	public function index(){

		$appid = 'wx3c484176a1ad105d';
		$appsecret = 'b314e4774f61a3ac2d81a82e8d71d93f';
		$code=$_GET['code'];
		$post_data=json_decode($_GET['state']);
		$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
		$res = $this->http_curl($url, 'get', 'json');
		//var_dump($post_data);
		$openId=$res['openid'];
		

		$user=$post_data->user;
		$user_id=M('player')->where(array('user'=>$user))->field('id')->find();

		if(!isset($user_id['id'])){
			$this->script('不存在该用户，请重新输入!');
		}

		//查出商品信息
		$goods_id=$post_data->name;
		$goods=M('goods')->where(array('id'=>$goods_id))->field('rmb,id,name')->find();
		if($goods){
			$this->goods_name=$goods['name'];
			$this->goods_price=$goods['rmb'];
			$order_id=$this->createOrderId();
			$this->insert_mysql($goods,$user_id,$order_id);
		}else{
			$this->script('请选择一个商品！');
		}


		//①、获取用户openid
		$tools = new \JsApiPay();
		//$openId = $tools->GetOpenid();


//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($goods['name']);
		$input->SetAttach("test");
		$input->SetOut_trade_no($order_id);
		$input->SetTotal_fee((int)$goods['rmb']);
		$input->SetProduct_id((int)$goods['id']);
		$input->SetTime_start(date("YmdHis"));

		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("test");
		$input->SetNotify_url("http://dwc.gametu.com/think/weixing/notify.php");
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId);
		$order = \WxPayApi::unifiedOrder($input);
		//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
		//$this->printf_info($order);

		$jsApiParameters = $tools->GetJsApiParameters($order);
		//var_dump($jsApiParameters);
		$this->jsApiParameters=$jsApiParameters;

//获取共享收货地址js函数参数
		$editAddress = $tools->GetEditAddressParameters();
		$this->editAddress=$editAddress;
		//var_dump($editAddress);die;
	    //$this->display();
		$pay_url="http://dwc.gametu.com/think/weixing/pay.php?jsApiParameters=$jsApiParameters&editAddress=$editAddress&goods_name=".$goods['name']."&goods_price=".$goods['rmb']."";
		header("location:".$pay_url);

	}







	//生成订单写入数据库
	public function insert_mysql($goods,$user_id,$order_id){
		$payinfo['uid'] = (int) $user_id['id'];
		$payinfo['order_id'] = $order_id;
		$payinfo['price'] = (float) $goods['rmb'];
		$payinfo['pay_type'] = (int)20;
		$payinfo['goods_id'] = (int)$goods['id'];
		$payinfo['version'] = 0;
		$payinfo['type'] = 0;
		$payinfo['optype'] = 1;
		$payinfo['is_send'] = 0;
		$payinfo['create_time'] = date('Y-m-d H:i:s',time());
		$payinfo['update_time'] = date('Y-m-d H:i:s',time());
		$msg=M('applypay')->add($payinfo);
		if(!$msg){
			$this->script('网络异常，请稍后再试！');
		}
		error_log(date("[Y-m-d H:i:s]")." -[".json_encode($payinfo).".\n\r",3,'error.log');
	}
	
	// 打印log
	public function log_result($file,$word)
	{
	    $fp = fopen($file,"a");
	    flock($fp, LOCK_EX) ;
	    fwrite($fp,"执行日期：".strftime("%Y-%m-%d-%H：%M：%S",time())."\n".$word."\n\n");
	    flock($fp, LOCK_UN);
	    fclose($fp);
	}

	//打印输出数组信息
	function printf_info($data)
	{
		foreach($data as $key=>$value){
			echo "<font color='#00ff55;'>$key</font> : $value <br/>";
		}
	}

}
?>